<template>
  <el-config-provider :locale="zhCn">
    <div class="page">
      <div class="toolbar">
        <el-form :inline="true" :model="filters" class="filters">
          <el-form-item label="模板版本代码">
            <el-input v-model="filters.template_version_code" placeholder="请输入" clearable />
          </el-form-item>
          <el-form-item label="名称">
            <el-input v-model="filters.name" placeholder="请输入" clearable />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="reload">查询</el-button>
            <el-button @click="resetFilters">重置</el-button>
          </el-form-item>
        </el-form>
        <div class="actions">
          <el-button type="primary" @click="openCreate">新建模版</el-button>
        </div>
      </div>

      <div class="table-area">
        <div class="table-container">
          <el-table :data="filteredList" style="width:100%" max-height="100%">
            <el-table-column prop="template_version_code" label="模板版本代码" min-width="200" />
            <el-table-column prop="name" label="名称" min-width="180" />
            <el-table-column prop="indicator_version_id" label="指标版本ID" min-width="220" />
            <el-table-column prop="word_template_mongo_id" label="Word模板MongoID" min-width="260" />
            <el-table-column fixed="right" label="操作" width="380">
              <template #default="{ row }">
                <el-button @click="openEdit(row)">编辑</el-button>
                <el-popconfirm title="确定删除该模版？" @confirm="remove(row)">
                  <template #reference>
                    <el-button type="danger">删除</el-button>
                  </template>
                </el-popconfirm>
                <el-button @click="viewDetail(row)">详情</el-button>
                <el-button @click="openClone(row)">克隆</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>

      <el-dialog v-model="showDialog" :title="dialogTitle" width="640px" destroy-on-close>
        <div v-if="cloneMode" class="clone-tip">
          将克隆模版基本信息与章节目录（模板大纲），请确认新建参数。
        </div>
        <el-form ref="formRef" :model="form" :rules="rules" label-width="130px">
          <el-form-item label="模板版本代码" prop="template_version_code"><el-input v-model="form.template_version_code" :disabled="!!editingId && !cloneMode" /></el-form-item>
          <el-form-item label="名称" prop="name"><el-input v-model="form.name" /></el-form-item>
          <el-form-item label="指标版本ID"><el-input v-model="form.indicator_version_id" /></el-form-item>
          <el-form-item label="Word模板MongoID"><el-input v-model="form.word_template_mongo_id" /></el-form-item>
        </el-form>
        <template #footer>
          <el-button @click="showDialog=false">取消</el-button>
          <el-button type="primary" :loading="saving" @click="submit">保存</el-button>
        </template>
      </el-dialog>
    </div>
  </el-config-provider>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import zhCn from 'element-plus/es/locale/lang/zh-cn'
import { ElMessage } from 'element-plus'
import { api } from '../../api/client'
import { useRouter } from 'vue-router'

interface TemplateItem {
  id: string
  template_version_code: string
  name: string
  indicator_version_id?: string
  word_template_mongo_id?: string
}

const list = ref<TemplateItem[]>([])
const filters = reactive({ template_version_code: '', name: '' })
const filteredList = computed(() => {
  let arr = list.value
  if (filters.template_version_code) arr = arr.filter(x => x.template_version_code?.includes(filters.template_version_code))
  if (filters.name) arr = arr.filter(x => x.name?.includes(filters.name))
  return arr
})
const router = useRouter()
const form = ref<Partial<TemplateItem>>({ template_version_code: '', name: '' })
const cloneMode = ref(false)
const cloningSource = ref<TemplateItem | null>(null)

async function load() {
  const resp = await api.get('/evaluation-templates/')
  list.value = resp.data || []
}

function openCreate() {
  dialogTitle.value = '新建模版'
  editingId.value = null
  form.value = { template_version_code: '', name: '', indicator_version_id: '', word_template_mongo_id: '' }
  showDialog.value = true
  cloneMode.value = false
  cloningSource.value = null
}

function openEdit(t: TemplateItem) {
  dialogTitle.value = '编辑模版'
  editingId.value = t.id
  form.value = { ...t }
  showDialog.value = true
  cloneMode.value = false
  cloningSource.value = null
}

async function remove(t: TemplateItem) {
  await api.delete(`/evaluation-templates/${t.id}`)
  list.value = list.value.filter((x) => x.id !== t.id)
}

function viewDetail(t: TemplateItem) {
  router.push(`/admin/evaluation-templates/${t.id}`)
}

function openClone(t: TemplateItem) {
  dialogTitle.value = '克隆模版'
  editingId.value = null
  cloningSource.value = t
  cloneMode.value = true
  form.value = {
    template_version_code: '',
    name: t.name,
    indicator_version_id: t.indicator_version_id || '',
    word_template_mongo_id: t.word_template_mongo_id || ''
  }
  showDialog.value = true
}

const showDialog = ref(false)
const dialogTitle = ref('')
const saving = ref(false)
const editingId = ref<string | null>(null)
const formRef = ref()
const rules = {
  template_version_code: [{ required: true, message: '请输入模板版本代码', trigger: 'blur' }],
  name: [{ required: true, message: '请输入名称', trigger: 'blur' }],
}

async function submit() {
  if (formRef.value) {
    const ok = await new Promise<boolean>((resolve) => formRef.value.validate((v: boolean) => resolve(v)))
    if (!ok) return
  }
  saving.value = true
  try {
    if (editingId.value && !cloneMode.value) {
      await api.put(`/evaluation-templates/${editingId.value}`, form.value)
      const idx = list.value.findIndex(x => x.id === editingId.value)
      if (idx >= 0) list.value[idx] = { ...(list.value[idx]), ...(form.value as any) }
      ElMessage.success('已保存')
    } else if (!editingId.value && !cloneMode.value) {
      const resp = await api.post('/evaluation-templates/', form.value)
      list.value.unshift(resp.data)
      ElMessage.success('已创建')
    } else if (cloneMode.value && cloningSource.value) {
      const resp = await api.post(`/evaluation-templates/${cloningSource.value.id}/clone`, form.value)
      list.value.unshift(resp.data)
      ElMessage.success('已克隆')
    }
    showDialog.value = false
  } catch (e: any) {
    const msg = e?.response?.data?.detail || '保存失败'
    ElMessage.error(msg)
  } finally {
    saving.value = false
    cloneMode.value = false
    cloningSource.value = null
  }
}

function reload() {}
function resetFilters() { filters.template_version_code = ''; filters.name = '' }

onMounted(load)
</script>

<style scoped>
.page { height: 100%; display: flex; flex-direction: column; box-sizing: border-box; overflow: hidden; }
.toolbar { flex-shrink: 0; display: flex; align-items: center; justify-content: space-between; gap: 12px; padding-bottom: 16px; box-sizing: border-box; }
.filters { flex: 1; }
.actions { flex-shrink: 0; }
.table-area { flex: 1; display: flex; flex-direction: column; min-height: 0; overflow: hidden; }
.table-container { flex: 1; overflow: hidden; display: flex; flex-direction: column; min-height: 0; position: relative; }
.table-container :deep(.el-table) { height: 100% !important; display: flex; flex-direction: column; flex: 1; }
.table-container :deep(.el-table__inner-wrapper) { height: 100% !important; display: flex; flex-direction: column; flex: 1; }
.table-container :deep(.el-table__header-wrapper) { flex-shrink: 0; height: auto !important; }
.table-container :deep(.el-table__body-wrapper) { flex: 1; overflow-y: auto !important; height: auto !important; min-height: 200px; }
.table-container :deep(.el-table__empty-block) { min-height: 200px; display: flex; align-items: center; justify-content: center; }
.clone-tip { margin-bottom: 10px; padding: 10px; background: #fff7e6; color: #8a6200; border: 1px solid #ffe58f; border-radius: 6px; }
@media (max-width: 768px) { .toolbar { flex-direction: column; align-items: stretch; } .filters { margin-bottom: 12px; } }
</style>